package com.hyt.it.ogt.pj.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.mapper.ItemScoreMapper;
import com.hyt.it.ogt.pj.model.entity.ItemScore;
import com.hyt.it.ogt.pj.model.entity.PaperItem;
import com.hyt.it.ogt.pj.model.vo.ItemScoreVo;
import com.hyt.it.ogt.pj.service.IItemScoreService;
import com.hyt.it.ogt.pj.service.IPaperItemService;

/**
 * <p>
 * 题目分数表 服务实现类
 * </p>
 *
 * @author qiaozj
 * @since 2020-07-09
 */
@Service
public class ItemScoreServiceImpl extends BaseServiceImpl<ItemScoreMapper, ItemScore> implements IItemScoreService {

    @Autowired
    ItemScoreMapper itemScoreMapper;
    
    @Autowired
    private IPaperItemService paperItemService;
    
    @Override
    public boolean deleteByProjectId(String projectId) {
        itemScoreMapper.deleteByProjectId(projectId);
        return true;
    }

    @Override
    public List<ItemScoreVo> getStudentItemScore(String projectId, String admissionNum) {
        List<ItemScoreVo> itemScoreVos = itemScoreMapper.getStudentItemScore(projectId, admissionNum);
        // 对相同的itemid去重合并
        Map<String, List<ItemScoreVo>> itemScoreVoVOMap = new HashMap<String, List<ItemScoreVo>>();
        if(CollectionUtils.isNotEmpty(itemScoreVos)) {
        	for (ItemScoreVo itemScoreVo : itemScoreVos) {
        		if(itemScoreVoVOMap.containsKey(itemScoreVo.getItemId())) {
        			List<ItemScoreVo> candidateSubjectiveScoreVOs = itemScoreVoVOMap.get(itemScoreVo.getItemId());
        			candidateSubjectiveScoreVOs.add(itemScoreVo);
        		}else {
        			List<ItemScoreVo> candidateSubjectiveScoreVOs = new ArrayList<ItemScoreVo>();
        			candidateSubjectiveScoreVOs.add(itemScoreVo);
        			itemScoreVoVOMap.put(itemScoreVo.getItemId(), candidateSubjectiveScoreVOs);
        		}
			}
        }
        
        // 对相同的items-scores取平均值
        List<ItemScoreVo> result = new ArrayList<>();
        if(MapUtils.isNotEmpty(itemScoreVoVOMap)) {
        	for (String  itemid : itemScoreVoVOMap.keySet()) {
        		PaperItem paperItem = paperItemService.getBaseMapper().selectById(itemid);
        		List<ItemScoreVo> candidateSubjectiveScoreVOs = itemScoreVoVOMap.get(itemid);
        		if(CollectionUtils.isNotEmpty(candidateSubjectiveScoreVOs)) {
        			ItemScoreVo candidateSubjectiveScoreVO = candidateSubjectiveScoreVOs.get(0);
        			BigDecimal subjectiveScore = BigDecimal.ZERO;
        			for (ItemScoreVo candidateSubjectiveScoreVO2 : candidateSubjectiveScoreVOs) {
        				if(null != candidateSubjectiveScoreVO2.getScore()) {
        					subjectiveScore = subjectiveScore.add(candidateSubjectiveScoreVO2.getScore());
        				}
					}
					BigDecimal pingjunScore = subjectiveScore.divide(new BigDecimal(candidateSubjectiveScoreVOs.size()), 2, BigDecimal.ROUND_HALF_UP);
        			candidateSubjectiveScoreVO.setScore(pingjunScore);
        			if(null != paperItem && StringUtils.isNotEmpty(paperItem.getTopicId())) {
        				candidateSubjectiveScoreVO.setItemId(paperItem.getTopicId());;
            			result.add(candidateSubjectiveScoreVO);
        			}
        		}
			}
        }
        return result;
    }
    
    @Override
    public List<ItemScoreVo> getStudentItemScore(String projectId, String admissionNum, String currUserId) {
        List<ItemScoreVo> itemScoreVos = itemScoreMapper.getStudentItemScoreByCurrUserId(projectId, admissionNum, currUserId);
        return itemScoreVos;
    }
    
    @Override
    public void deleteStudentScoreByTaskIdAndEncodeId(String taskId, String encodeId) {
        itemScoreMapper.deleteStudentScoreByTaskIdAndEncodeId(taskId, encodeId);
    }

    @Override
    public void deleteStudentScoreByTaskIdAndEncodeIdAndUserId(String taskId, String encodeId, String userId) {
        itemScoreMapper.deleteStudentScoreByTaskIdAndEncodeIdAndUserId(taskId, encodeId,userId);
    }

    @Override
    public List<ItemScoreVo> getStudentItemScoreByAdmissionNums(String projectId, List<String> admissionNums) {
        List<ItemScoreVo> itemScoreVos = itemScoreMapper.getStudentItemScores(projectId, admissionNums, null);
        // 对相同的itemid去重合并
        Map<Pair<String, String>, List<ItemScoreVo>> itemScoreVoVOMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(itemScoreVos)) {
            for (ItemScoreVo itemScoreVo : itemScoreVos) {
                Pair<String, String> pairKey = Pair.of(itemScoreVo.getEncodeId(), itemScoreVo.getItemId());
                if (itemScoreVoVOMap.containsKey(pairKey)) {
                    List<ItemScoreVo> candidateSubjectiveScoreVOs = itemScoreVoVOMap.get(pairKey);
                    candidateSubjectiveScoreVOs.add(itemScoreVo);
                } else {
                    List<ItemScoreVo> candidateSubjectiveScoreVOs = new ArrayList<>();
                    candidateSubjectiveScoreVOs.add(itemScoreVo);
                    itemScoreVoVOMap.put(pairKey, candidateSubjectiveScoreVOs);
                }
            }
        }
        // 对相同的items-scores取平均值
        List<ItemScoreVo> result = new ArrayList<>();
        if (MapUtils.isNotEmpty(itemScoreVoVOMap)) {
            List<PaperItem> paperItemList = paperItemService.getBaseMapper().selectBatchIds(itemScoreVoVOMap.keySet().stream().map(vo -> vo.getSecond()).collect(Collectors.toList()));
            if (!paperItemList.isEmpty()) {
                paperItemList.forEach(vo -> itemScoreVoVOMap.entrySet().forEach(m -> {
                    if (m.getKey().getSecond().equals(vo.getId())) {
                        List<ItemScoreVo> candidateSubjectiveScoreVOs = m.getValue();
                        if (CollectionUtils.isNotEmpty(candidateSubjectiveScoreVOs)) {
                            ItemScoreVo candidateSubjectiveScoreVO = candidateSubjectiveScoreVOs.get(0);
                            BigDecimal subjectiveScore = BigDecimal.ZERO;
                            for (ItemScoreVo itemScoreVo : candidateSubjectiveScoreVOs) {
                                if (null != itemScoreVo.getScore()) {
                                    subjectiveScore = subjectiveScore.add(itemScoreVo.getScore());
                                }
                            }
                            BigDecimal pingjunScore = subjectiveScore.divide(new BigDecimal(candidateSubjectiveScoreVOs.size()), 2, BigDecimal.ROUND_HALF_UP);
                            candidateSubjectiveScoreVO.setScore(pingjunScore);
                            if (StringUtils.isNotEmpty(vo.getTopicId())) {
                                candidateSubjectiveScoreVO.setItemId(vo.getTopicId());
                                result.add(candidateSubjectiveScoreVO);
                            }
                        }
                    }
                }));
            }
        }
        return result;
    }

}
